<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\ScoreRuleController;
use App\Models\Activity;
use App\Models\ActivityApply;
use App\Models\UserInfo;
use App\Models\UserWechatInfo;
use App\Validate\ActivityApplyValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 活动申请类
 */
class ActivityApplyController extends CommonController
{
    protected $model;
    protected $activityModel;
    protected $validate;

    protected $score_type = 4;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ActivityApply();
        $this->activityModel = new Activity();
        $this->validate = new ActivityApplyValidate();
    }

    /** 
     * 活动申请列表
     * @param act_id int 活动id
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param status int 报名状态    1.已通过  3.已拒绝  4.审核中
     */
    public function activityApplyList()
    {
        //处理逾期未签到的数据
        $this->model->checkApplyStatus();

        $limit = $this->request->limit ? $this->request->limit : 10;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $keywords = $this->request->keywords;
        $status = $this->request->status;
        $act_id = $this->request->act_id;

        $activity = $this->activityModel->where('id', $act_id)->first();

        if (!$activity) {
            return $this->returnApi(201, "参数传递错误");
        }

        $status = empty($status) ? [1, 3, 4] : $status;
        $res = $this->model->activityApplyUserList($act_id, $status, null, $keywords, null, null, null, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /** 
     * 活动人员列表
     * @param act_id int 活动id
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param keywords_type string 关键词类型 username(名称) id_card(身份证) tel(电话) reader_id(读者证) qr_code(二维码)
     * @param is_sign 今日是否签到 0全部 1已签到 2未签到  默认等于2
     * @param start_time 报名开始时间
     * @param end_time 报名结束时间
     */
    public function activityApplyUser()
    {
        $limit = $this->request->limit ? $this->request->limit : 10;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $keywords = $this->request->keywords;
        $keywords_type = $this->request->keywords_type ? $this->request->keywords_type : '';
        $act_id = $this->request->act_id;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $is_sign = $this->request->is_sign ? $this->request->is_sign : 0;

        $res = $this->model->activityApplyUserList($act_id, 1, $keywords_type, $keywords, $start_time, $end_time, $is_sign, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        return $this->returnApi(200, "查询成功", true, $res);
    }


    /** 
     * 审核通过 和 拒绝
     * @param id int 申请id
     * @param status int 状态  1.已通过 3.已拒绝 
     * @param reason string 拒绝理由
     */
    public function agreeAndRefused()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('check')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->status == 3 && empty($this->request->reason)) {
            return $this->returnApi(201, "拒绝理由不能为空");
        }

        DB::beginTransaction();
        try {
            $res = $this->model->agreeAndRefused($this->request->id, $this->request->status, $this->request->reason);

            /*消息推送*/
            $msg = $this->request->status == 1 ? '通过' : '拒绝';
            if ($this->request->status == 1) {
                $remark = '您报名的活动：【' . $res->conActivity->title . '】已' . $msg;
                $system_id = $this->systemAdd('活动报名已' . $msg, $res->user_id, $res->account_id, 5, $this->request->id, $remark);
            } else {
                $remark =  '您报名的活动：【' . $res->conActivity->title . '】已' . $msg . '拒绝理由为：' . $this->request->reason;
                $system_id = $this->systemAdd('活动报名已' . $msg, $res->user_id, $res->account_id, 5, $this->request->id, $remark);
                if (!empty($res->score)) {
                    $score_rule = new ScoreRuleController();
                    $score_msg = $score_rule->getScoreMsg($res->score);
                    $score_rule->scoreReturn($this->score_type, $res->score, $res->user_id, $res->account_id, '参加活动被拒绝，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id, '参加活动被拒绝');
                }
            }

            //减少报名人数
            if ($this->request->status == 3) {
                $act_id = $this->model->where('id', $this->request->id)->value('act_id');
                $this->activityModel->where('id', $act_id)->decrement('apply_number'); //减少已报名人数
            }


            //添加推送模板消息
            if (config('other.is_send_wechat_temp_info')) {
                $act_info = Activity::select('title', 'start_time')->where('id', $res->act_id)->first();

                $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                $data['openid'] = UserWechatInfo::getOpenIdByUserId($res['user_id']);
                $data['content'] = '审核已' . $msg;
                $data['act_name'] = $act_info['title'];
                $data['status'] =  $msg;
                $data['time'] =  $act_info['start_time'];
                $data['addr'] =  $act_info['address'];
                $data['remark'] = $remark;
                $data['create_time'] = date('Y-m-d H:i:s');

                $data['link'] = '?booktype=2&id=' . $this->request->id;
                $tempInfoObj->sendActivityCheckInfo($data, $this->request->status);
            }

            DB::commit();
            return $this->returnApi(200, $msg . "成功", true);
        } catch (Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 活动报名违规 与 取消违规操作
     * @param id int 申请id
     * @param reason string 违规原因
     */
    public function violateAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('violate_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $res = $this->model->violateAndCancel($this->request->id, $this->request->reason);
            /*消息推送*/
            if ($res->is_violate == 2) {
                $system_id = $this->systemAdd('活动已违规', $res->user_id, $res->account_id, 6, $res->id, '您申请的活动：【' . $res->conActivity->title . '】已违规，违规理由为：' . $this->request->reason);

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg($res->score);
                //     $score_rule->scoreReturn($this->score_type, $res->score,$res->user_id, $res->account_id, '活动已违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id, '活动已违规');
                // }
            } else {
                $system_id = $this->systemAdd('活动已取消违规', $res->user_id, $res->account_id, 6, $res->id, '您申请的活动：【' . $res->conActivity->title . '】已取消违规');

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg(-$res->score); //相反积分
                //     $score_rule->scoreReturn($this->score_type, $res->score,$res->user_id, $res->account_id, '活动已违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id, '活动取消违规');
                // }
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "操作成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
